package com.gemme.gemme.wode;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.chat.ChatActivity;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.shequ.ShequDetailActivity;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.Topview;
import com.hyphenate.easeui.EaseConstant;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class ShequPsonDetActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shequ2_detail);
        initTop();
        initView();
        initIntentData();
        getDataZydy();
        getShequDatas();
    }
    int userId;
    private void
    initIntentData() {
        try {
            userId = getIntent().getIntExtra("data",-1);
        }catch (Exception e){

        }
    }

    TextView tv_dongtai;
    TextView tv_fans;
    TextView tv_guanzhu;

    RecyclerView mRecyclerView;
    ImageView iv_head;
    TextView tv_name;
    LinearLayout ll_desc;
    TextView tv_desc;
    TextView tv_time;
    ImageView iv_chat;
    ImageView iv_guanzhu;

    @Override
    protected void onResume() {
        super.onResume();
        setrecycler();
        initIntentData();
        getDataZydy();
        getShequDatas();
    }

    private void initView() {
        iv_head = findViewById(R.id.iv_head);
        tv_name = findViewById(R.id.tv_name);
        tv_fans = findViewById(R.id.tv_fans);
        tv_dongtai = findViewById(R.id.tv_dongtai);
        tv_guanzhu = findViewById(R.id.tv_guanzhu);
        tv_desc = findViewById(R.id.tv_desc);
        ll_desc = findViewById(R.id.ll_desc);
        tv_time = findViewById(R.id.tv_time);

        iv_chat = findViewById(R.id.iv_chat);
        iv_guanzhu = findViewById(R.id.iv_guanzhu);

        tv_fans.setOnClickListener(this);
        tv_guanzhu.setOnClickListener(this);
        mRecyclerView = findViewById(R.id.recycler);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        //list滚动到中间位置
        new LinearSnapHelper().attachToRecyclerView(mRecyclerView);
        setrecycler();

        iv_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //进入聊天界面
                Intent intent = new Intent(mContext, ChatActivity.class);

                if(TextUtils.isEmpty(mobile)){
                    Toast.makeText(mContext, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent.putExtra(EaseConstant.EXTRA_USER_ID, mobile);
                startActivity(intent);
            }
        });

        iv_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toGuanzhu(userId + "");
            }
        });
    }
    float sh_width ;
    float screen_width;
    private void setrecycler() {
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        Point point = new Point();
        defaultDisplay.getSize(point);

        screen_width = point.x;
        sh_width = screen_width / 2;


      /*  ShequAdapter shequAdapter = new ShequAdapter();
        mRecyclerView.setAdapter(shequAdapter);*/
        initListener();
       /* mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                onScrolledChangedCallback();
            }
        });*/
    }

    private void initListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // dx>0则表示右滑, dx<0表示左滑, dy<0表示上滑, dy>0表示下滑

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取第一个可见view的位置
                    int firstItemPosition = linearManager.findFirstVisibleItemPosition();

                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();

                    if(lastItemPosition - firstItemPosition == 2){
                        currentPosition = firstItemPosition + 1;
                    }else{
                        currentPosition = firstItemPosition;
                    }
                }

                onScrolledChangedCallback();
                controlBottom();
            }
        });


    }

    private void controlBottom() {
        try {
            ZydyBean.DataBean.RecordsBean bean = (ZydyBean.DataBean.RecordsBean) selectView.getTag();
            if(bean!=null){
                Object cdescribe = bean.getCdescribe();
                tv_desc.setText(StrUtil.noNUll(cdescribe));
                String createTime = bean.getCreateTime();
                tv_time.setText(createTime.substring(0,10));
                if (TextUtils.isEmpty(StrUtil.noNUll(cdescribe))) {
                    ll_desc.setVisibility(View.GONE);
                } else {
                    ll_desc.setVisibility(View.VISIBLE);
                }
            }else {
                tv_desc.setVisibility(View.GONE);
                tv_time.setVisibility(View.GONE);
            }
          /*  Date date = GmDateUtil.stringToDate(bean.getCreateTime(), GmDateUtil.format_ymdhms);
            Date currentdate = new Date();

            long xiaoshi = (currentdate.getTime() - date.getTime()) / (1000 * 60 * 60);//小时数
//            long fenzhong = (currentdate.getTime() - date.getTime()) % (1000 * 60 * 60);//小时数
            tv_time.setText(xiaoshi + "小时前");*/
        }catch (Exception e){

        }

    }


    int currentPosition = 0;
    private void onScrolledChangedCallback() {
        View leftView = null;
        View currentView;
        View rightView = null;
        if(currentPosition < 0)
            return;

        if (currentPosition > 0) {
            leftView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition - 1);
        }
        currentView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition);
        if (currentPosition < mRecyclerView.getAdapter().getItemCount() - 1) {
            rightView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition + 1);
        }

        try {
          /*  leftView.setScaleY(0.8f);
            currentView.setScaleY(1.1f);
            rightView.setScaleY(0.8f);*/

            control(leftView);
            control(currentView);
            control(rightView);


        }catch (Exception e){

        }
    }

    View selectView;

    private void control(View view) {
        if(view == null)
            return;
        float left = view.getLeft();
        float right = view.getRight();
        System.out.println();

        float view_half = (left + right) / 2;
        float abs = Math.abs(view_half - sh_width);
        if(abs >=  sh_width){
            view.setScaleY(0.8f);
        }else{
            //  540
            float scale_size = 1 - Math.abs((((sh_width - view_half) / sh_width) * (1 - 0.8f)));
            view.setScaleY(scale_size);
        }


        if(sh_width > left && sh_width < right){

            selectView = view;
        }
    }


    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("个人页");
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_fans:
                //todo 暂时去掉社区个人中心进入粉丝和关注列表
//                startActivity(new Intent(mContext,ShequFansActivity.class));
                break;

            case R.id.tv_guanzhu:
                //todo 暂时去掉社区个人中心进入粉丝和关注列表
//                startActivity(new Intent(mContext,ShequFansActivity.class));
                break;
                //todo
               /* case R.id.ll_shequ_detail:
                startActivity(new Intent(mContext,ShequDetailActivity.class));
                break;*/
        }
    }

    public  class ShequAdapter extends RecyclerView.Adapter<ShequAdapter.ViewHolder> {


        private List<ZydyBean.DataBean.RecordsBean> adapterList;

        public ShequAdapter(List<ZydyBean.DataBean.RecordsBean> adapterList) {

            this.adapterList = adapterList;
        }

        @NonNull
        @Override
        public ShequAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.item_shequ_person2, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = DpUtil.dip2px(mContext,15);
            layoutParams.rightMargin = DpUtil.dip2px(mContext,15);
            inflate.setLayoutParams(layoutParams);
            return new ShequAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ShequAdapter.ViewHolder holder, int position) {

            try {
                if (position == 0) {
                    holder.view_add_paddding.setVisibility(View.VISIBLE);
                } else {
                    holder.view_add_paddding.setVisibility(View.GONE);
                }

                if (position == 10 - 1) {
                    holder.view_add_paddding_right.setVisibility(View.VISIBLE);
                } else {
                    holder.view_add_paddding_right.setVisibility(View.GONE);
                }

                ZydyBean.DataBean.RecordsBean recordsBean = adapterList.get(position);
                String coverPath = recordsBean.getCoverPath();

                holder.itemView.setTag(recordsBean);
                if(!TextUtils.isEmpty(coverPath)){
                    Glide.with(mContext).load(coverPath).into(holder.iv_picture);

                }
                String videoPath = recordsBean.getVideoPath();
                if(!TextUtils.isEmpty(videoPath)){
                   /* Glide.with(mContext)
                            .load( Uri.fromFile( new File( videoPath ) ) )
                            .into( holder.iv_picture);*/

                    //可以参考Glide，内部也是封装了MediaMetadataRetriever
//                    .error(R.mipmap.xxx2)
//                            .placeholder(R.mipmap.xxx1)
                    Glide.with(getApplicationContext())
                            .setDefaultRequestOptions(
                                    new RequestOptions()
                                            .frame(1000000)
                                            .centerCrop()
                                            )
                            .load(videoPath)
                            .into(holder.iv_picture);
                }



                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int id = recordsBean.getId();
                        Intent intent = new Intent(mContext, ShequDetailActivity.class);
                        intent.putExtra("data",id);
                        startActivity(intent);
                    }
                });


            }catch (Exception e){

            }


        }

        @Override
        public int getItemCount() {
            return adapterList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            View view_add_paddding;
            View view_add_paddding_right;
            ImageView iv_picture;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                view_add_paddding = itemView.findViewById(R.id.view_add_paddding);
                view_add_paddding_right = itemView.findViewById(R.id.view_add_paddding_right);
                iv_picture = itemView.findViewById(R.id.iv_picture);
            }
        }
    }

    private void getDataZydy() {
        String url = DataManager.BaseUrl + "community/appcusers/zydynamiclist?current=1&size=1000" +
                "&userId=" + userId;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {

                    System.out.println("");
                    ZydyBean zydyBean = JSON.parseObject(response, ZydyBean.class);
                    List<ZydyBean.DataBean.RecordsBean> records = zydyBean.getData().getRecords();
                    if(records == null)
                        return;
                    mRecyclerView.setAdapter(new ShequAdapter(records));
                }catch (Exception e){

                }
                System.out.println("");
            }
        });
    }

    String mobile;
    private void getShequDatas() {
       /* String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
        if(TextUtils.isEmpty(userId))
            return;*/
        String url = DataManager.BaseUrl + "community/appcusers/comunityuser?userId=" + userId;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {

                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject data = jsonObject.getJSONObject("data");
                    String fansCounts = data.getString("fansCounts");
                    String followCounts = data.getString("followCounts");
                    String dynamicCounts = data.getString("dynamicCounts");

                    String headImg = data.getString("headImg");
                    String nickName = data.getString("nickName");
                    String signature = data.getString("signature");

                    mobile = data.getString("mobile");
                    System.out.println("");
                    tv_dongtai.setText("动态" + dynamicCounts);
                    tv_fans.setText("粉丝" + fansCounts);
                    tv_guanzhu.setText("关注" + followCounts);
                    if(dynamicCounts.equals("0")){
                        tv_time.setVisibility(View.GONE);
                        ll_desc.setVisibility(View.GONE);
                    }else {
                        tv_time.setVisibility(View.VISIBLE);
                        ll_desc.setVisibility(View.VISIBLE);
                    }
                    tv_name.setText(StrUtil.noNUll(nickName));
                    String headImgUrl = StrUtil.noNUll(headImg);
                    if(!TextUtils.isEmpty(headImgUrl))
                        Glide.with(mContext).load(StrUtil.noNUll(headImgUrl)).transform(new GlideCircleTransform(mContext))
                                .into(iv_head);
                }catch (Exception e){

                }
                System.out.println("");
            }
        });
    }

    private void toGuanzhu(String userId) {
        try {
            String url = DataManager.BaseUrl + "community/appcusersfans/focuson?userId=" + userId;

            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try {

//                        getDataS();
                        String msg = (new JSONObject(response)).getString("msg");
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        getShequDatas();
                    }catch (Exception e){

                    }
                    System.out.println("");
                }
            });
        }catch (Exception e){

        }

    }


}